package weaver.splittable.db.mysql;

import weaver.splittable.db.STCreateTriggerUtil;
import weaver.splittable.db.STDBConstants;

public class STMysqlCreateTriggerUtil implements STCreateTriggerUtil {

    private static final String CREATE_TRIGGER_INSERT_SQL =
            "CREATE TRIGGER %s AFTER INSERT ON %s FOR EACH ROW \n"
                    + "BEGIN \n INSERT INTO "+ STDBConstants.DATA_CHANGE_TABLE_NAME +"(event_type, table_name, data_id_column, data_id, synced, create_time, sync_time) VALUES('insert', '%s', '%s', :NEW.%s, '0', DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%S'), null); \n"+
                    "END;";

    private static final String CREATE_TRIGGER_UPDATE_SQL =
            "CREATE TRIGGER %s AFTER UPDATE ON %s FOR EACH ROW \n"
                    + "BEGIN \n INSERT INTO "+ STDBConstants.DATA_CHANGE_TABLE_NAME +"(event_type, table_name, data_id_column, data_id, synced, create_time, sync_time) VALUES('update', '%s', '%s', :NEW.%s, '0', DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%S'), null); \n"+
                    "END;";

    private static final String CREATE_TRIGGER_DELETE_SQL =
            "CREATE TRIGGER %s AFTER DELETE ON %s FOR EACH ROW \n"
                    + "BEGIN \n INSERT INTO "+ STDBConstants.DATA_CHANGE_TABLE_NAME +"(event_type, table_name, data_id_column, data_id, synced, create_time, sync_time) VALUES('delete', '%s', '%s', :OLD.%s, '0', DATE_FORMAT(NOW(), '%Y-%m-%d %H:%i:%S'), null); \n"+
                    "END;";

    @Override
    public String createTriggerInsert(String tableName, String dataIdColumn) {
        String triggerInsertName = tableName + "_ins";
        if (tableName.length() > 20) {
            triggerInsertName = tableName.substring(0, 19) + "_ins";
        }
        return String.format(CREATE_TRIGGER_INSERT_SQL, triggerInsertName, tableName, tableName, dataIdColumn, dataIdColumn);
    }

    @Override
    public String createTriggerUpdate(String tableName, String dataIdColumn) {
        String triggerUpdateName = tableName + "_up";
        if (tableName.length() > 20) {
            triggerUpdateName = tableName.substring(0, 19) + "_up";
        }
        return String.format(CREATE_TRIGGER_UPDATE_SQL, triggerUpdateName, tableName, tableName, dataIdColumn, dataIdColumn);
    }

    @Override
    public String createTriggerDelete(String tableName, String dataIdColumn) {
        String triggerDeleteName = tableName + "_del";
        if (tableName.length() > 20) {
            triggerDeleteName = tableName.substring(0, 19) + "_del";
        }
        return String.format(CREATE_TRIGGER_DELETE_SQL, triggerDeleteName, tableName, tableName, dataIdColumn, dataIdColumn);
    }
}
